package com.jake.mallcrud.controller;

import com.jake.mallcrud.service.UserService;
import com.jake.mallmodel.entity.User;
import com.jake.mallmodel.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("users")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 查找所有用户
     * @return
     */
    @GetMapping
    public List<User> findAllUsers() {
        return userService.findAllUsers();
    }

    /**
     * 查找所有用户信息
     * @return
     */
    @GetMapping("info")
    public List<User> findAllUserInfo() {
        return userService.findAllUserInfo();
    }

    /**
     * 通过id查找用户
     * @param uid
     * @return
     */
    @GetMapping("{uid}")
    public User findUserById(@PathVariable Integer uid) {
        return userService.findUserById(uid);
    }

    /**
     * 通过id查找用户信息
     * @param uid
     * @return
     */
    @GetMapping("info/{uid}")
    public UserInfo findUserInfoById(@PathVariable Integer uid) {
        return userService.findUserInfoById(uid);
    }

    /**
     * 通过用户名和公司名查找用户
     * @param username
     * @param cname
     * @return
     */
    @GetMapping("info/{cname}/{username}")
    public List<UserInfo> findUserInfoByUsernameAndCname(@PathVariable String username, @PathVariable String cname) {
        return userService.findUserInfoByUsernameAndCname(username, cname);
    }

    /**
     * 新增用户
     * @param user
     * @return
     */
    @PostMapping
    public String createUser(@RequestBody User user) {
        if (user != null) {
            userService.createUser(user);
            return "添加用户成功";
        } else {
            return "添加用户失败";
        }
    }

    /**
     * 修改用户
     * @param user
     * @return
     */
    @PutMapping
    public String updateUser(@RequestBody User user) {
        User userInDb = userService.findUserById(user.getUid());
        if (userInDb != null) {
            userService.updateUser(user);
            return "更新用户成功";
        } else {
            return "更新用户失败";
        }
    }

    /**
     * 删除用户
     * @param uid
     * @return
     */
    @DeleteMapping("{uid}")
    public String removeUserById(@PathVariable Integer uid) {
        User user = userService.findUserById(uid);
        if (user == null) {
            return "数据库中不存在id为" + uid + "的用户";
        } else {
            userService.removeUserById(uid);
            return "删除成功";
        }
    }

}
